package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.format.FastDateFormat;
import com.zhijian.medical.dao.local.SkillTrainingMapper;
import com.zhijian.medical.entity.po.SkillTraining;
import com.zhijian.medical.entity.vo.request.FileSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.FileSearchVo;
import com.zhijian.medical.entity.vo.request.SkillTrainingSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.SkillTrainingSearchVo;
import com.zhijian.medical.entity.vo.response.FileVo;
import com.zhijian.medical.entity.vo.response.SkillTrainingVo;
import com.zhijian.medical.enums.FileTypeEnum;
import com.zhijian.medical.service.FileService;
import com.zhijian.medical.service.SkillTrainingService;
import com.zhijian.util.AssertUtil;
import com.zhijian.util.page.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 技能培训-医师诊断分级授权（变更）申请表业务处理层
 *
 * @author auto
 * @version: 1.0
 * @date 2024-08-22 13:24:54
 */
@Slf4j
@Service
public class SkillTrainingServiceImpl implements SkillTrainingService {

    @Autowired
    private SkillTrainingMapper mapper;

    @Autowired
    private FileService fileService;

    @Override
    public SkillTraining selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public SkillTrainingVo selectVoById(Long id) {
        SkillTrainingVo skillTrainingVo = mapper.selectVoById(id);
        if (Objects.isNull(skillTrainingVo)) {
            return null;
        }
        //图片文件地址数组
        List<FileVo> picFileVos = fileService.selectList(FileSearchVo.builder()
                .dataId(skillTrainingVo.getId())
                .type(FileTypeEnum.SKILL_TRAINING.getCode().byteValue())
                .build());
        if (CollectionUtil.isNotEmpty(picFileVos)) {
            skillTrainingVo.setPicFilePathList(picFileVos.stream().map(fileVo -> {
                FileSaveOrUpdateVo fileSaveOrUpdateVo = new FileSaveOrUpdateVo();
                fileSaveOrUpdateVo.setFileName(fileVo.getName());
                fileSaveOrUpdateVo.setFilePath(fileVo.getPath());
                return fileSaveOrUpdateVo;
            }).collect(Collectors.toList()));
        }
        return skillTrainingVo;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByIdList(List<Long> idList) {
        if (CollectionUtil.isEmpty(idList)) {
            return;
        }
        mapper.deleteByIdList(idList);
    }

    @Override
    public Long insert(SkillTraining skillTraining) {
        Date now = new Date();
        skillTraining.setCreateTime(now);
        skillTraining.setUpdateTime(now);
        return mapper.insert(skillTraining) > 0 ? skillTraining.getId() : 0L;
    }

    @Override
    public Long insertSelective(SkillTraining skillTraining) {
        Date now = new Date();
        skillTraining.setCreateTime(now);
        skillTraining.setUpdateTime(now);
        return mapper.insertSelective(skillTraining) > 0 ? skillTraining.getId() : 0L;
    }

    @Override
    public boolean update(SkillTraining skillTraining) {
        Date now = new Date();
        skillTraining.setUpdateTime(now);
        return mapper.updateByPrimaryKey(skillTraining) != 0;
    }

    @Override
    public boolean updateByPrimaryKeySelective(SkillTraining record) {
        Date now = new Date();
        record.setUpdateTime(now);
        return mapper.updateByPrimaryKeySelective(record) != 0;
    }

    @Override
    public boolean save(SkillTrainingSaveOrUpdateVo saveOrUpdateVo) {
        SkillTraining skillTraining = new SkillTraining();
        BeanUtils.copyProperties(saveOrUpdateVo, skillTraining);
        return this.insert(skillTraining) != 0;
    }

    @Override
    public boolean modify(SkillTrainingSaveOrUpdateVo saveOrUpdateVo) {
        SkillTraining old = this.selectById(saveOrUpdateVo.getId());
        AssertUtil.notNull(old, "此数据不存在或者已被删除");
        SkillTraining skillTraining = new SkillTraining();
        BeanUtils.copyProperties(saveOrUpdateVo, skillTraining);
        return this.update(skillTraining);
    }

    @Override
    public SkillTrainingVo selectOne(SkillTrainingSearchVo skillTrainingSearchVo) {
        return mapper.selectOne(skillTrainingSearchVo);
    }

    @Override
    public Integer count(SkillTrainingSearchVo skillTrainingSearchVo) {
        return mapper.count(skillTrainingSearchVo);
    }

    @Override
    public List<SkillTrainingVo> selectList(SkillTrainingSearchVo skillTrainingSearchVo) {
        List<SkillTrainingVo> skillTrainingVos = mapper.selectList(skillTrainingSearchVo);
        if (CollectionUtil.isEmpty(skillTrainingVos)) {
            return Collections.emptyList();
        }
        for (SkillTrainingVo skillTrainingVo : skillTrainingVos) {
            //图片文件地址数组
            List<FileVo> picFileVos = fileService.selectList(FileSearchVo.builder()
                    .dataId(skillTrainingVo.getId())
                    .type(FileTypeEnum.SKILL_TRAINING.getCode().byteValue())
                    .build());
            if (CollectionUtil.isNotEmpty(picFileVos)) {
                skillTrainingVo.setPicFilePathList(picFileVos.stream().map(fileVo -> {
                    FileSaveOrUpdateVo fileSaveOrUpdateVo = new FileSaveOrUpdateVo();
                    fileSaveOrUpdateVo.setFileName(fileVo.getName());
                    fileSaveOrUpdateVo.setFilePath(fileVo.getPath());
                    return fileSaveOrUpdateVo;
                }).collect(Collectors.toList()));
            }
        }
        return skillTrainingVos;
    }

    @Override
    public Page<SkillTrainingVo> selectPage(SkillTrainingSearchVo skillTrainingSearchVo) {
        AssertUtil.check(Objects.isNull(skillTrainingSearchVo.getPageNum()) || Objects.isNull(skillTrainingSearchVo.getPageSize()), "分页参数不能为空");
        //先直接查总数
        int count = count(skillTrainingSearchVo);
        //分页
        Page<SkillTrainingVo> page = new Page<>(true, count, skillTrainingSearchVo.getPageNum(), skillTrainingSearchVo.getPageSize());
        skillTrainingSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<SkillTrainingVo> responseVos = this.selectList(skillTrainingSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public boolean insertBatch(List<SkillTraining> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }

    @Override
    public void deleteByCondition(SkillTrainingSearchVo skillTrainingSearchVo) {
        //慎重用此方法！！
        mapper.deleteByCondition(skillTrainingSearchVo);
    }

    @Override
    public boolean savePic(Long id, List<FileSaveOrUpdateVo> fileSaveOrUpdateVos) {
        fileService.deleteByCondition(FileSearchVo.builder()
                .dataId(id)
                .type(FileTypeEnum.TEACH_PIC.getCode().byteValue())
                .build());
        fileService.insertBatch(fileSaveOrUpdateVos, FileTypeEnum.TEACH_PIC.getCode().byteValue(), id);
        return false;
    }

    public static final String CODE_PREFIX = "BLK-SOP-007-02-004";

    @Override
    public String selectMaxCode() {
//        return mapper.selectMaxCodeByDay(DateUtil.formatDate(new Date()));
        //todo 废弃
        return null;
    }

    @Override
    public String createNextCode() {
        String maxCode = this.selectMaxCode();
        if (StringUtils.isBlank(maxCode)) {
            return String.format("%s-%s-1", CODE_PREFIX, DateUtil.format(new Date(), FastDateFormat.getInstance("yyyyMMdd")));
        }
        String[] maxCodeArray = maxCode.split("-");
        Integer i = Integer.valueOf(maxCodeArray[maxCodeArray.length - 1]);
        i++;
        return String.format("%s-%s-%s", CODE_PREFIX, DateUtil.format(new Date(), FastDateFormat.getInstance("yyyyMMdd")), i);
    }

}